<template>
  <div class="profile-page">
    <!-- Header -->
    <van-nav-bar title="Profile" fixed placeholder>
      <template #right>
        <van-icon name="replay" size="18" @click="refreshUserData" :class="{ 'rotating': loading }" />
        <van-icon name="setting-o" size="18" @click="goToSettings" style="margin-left: 12px;" />
      </template>
    </van-nav-bar>

    <!-- User Info Card -->
    <div class="user-info-card">
      <div class="user-avatar">
        <van-image :src="userInfo?.avatar || '/default-avatar.png'" width="80" height="80" round fit="cover"
          :key="userInfo?.avatar" @click="changeAvatar" />
        <van-icon name="photograph" class="avatar-edit-icon" @click="changeAvatar" />
      </div>
      <div class="user-details">
        <h2 class="username">{{ userInfo?.username || 'User' }}</h2>
        <p class="user-bio">{{ userInfo?.bio || 'No bio yet' }}</p>
        <div class="user-stats">
          <div class="stat-item">
            <div class="stat-value">{{ userStats.level }}</div>
            <div class="stat-label">Level</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ userStats.totalPoints }}</div>
            <div class="stat-label">Points</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ userStats.streak }}</div>
            <div class="stat-label">Streak</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Progress Overview -->
    <div class="progress-overview">
      <h3 class="section-title">Progress Overview</h3>
      <div class="progress-cards">
        <div class="progress-card">
          <div class="card-header">
            <van-icon name="play-circle-o" color="#667eea" />
            <span>Training Sessions</span>
          </div>
          <div class="card-content">
            <div class="progress-number">{{ userStats.totalSessions }}</div>
            <div class="progress-subtitle">Completed</div>
            <van-progress :percentage="sessionProgress" stroke-width="4" />
          </div>
        </div>

        <div class="progress-card">
          <div class="card-header">
            <van-icon name="medal-o" color="#f39c12" />
            <span>Achievements</span>
          </div>
          <div class="card-content">
            <div class="progress-number">{{ userStats.achievements }}</div>
            <div class="progress-subtitle">Unlocked</div>
            <van-progress :percentage="achievementProgress" stroke-width="4" />
          </div>
        </div>
      </div>
    </div>

    <!-- Menu Items -->
    <div class="menu-section">
      <van-cell-group inset>
        <van-cell title="Training History" icon="clock-o" is-link @click="goToTrainingHistory" />
        <van-cell title="Achievements" icon="medal-o" is-link @click="goToAchievements" />
        <van-cell title="My Posts" icon="chat-o" is-link @click="goToMyPosts" />
        <van-cell title="Favorites" icon="star-o" is-link @click="goToFavorites" />
      </van-cell-group>
    </div>

    <!-- Settings Section -->
    <div class="settings-section">
      <van-cell-group inset>
        <van-cell title="Account Settings" icon="manager-o" is-link @click="goToAccountSettings" />
        <van-cell title="Privacy Settings" icon="shield-o" is-link @click="goToPrivacySettings" />
        <van-cell title="Help & Support" icon="question-o" is-link @click="goToHelp" />
      </van-cell-group>
    </div>

    <!-- Logout Button -->
    <div class="logout-section">
      <van-button type="danger" block round @click="handleLogout" :loading="logoutLoading">
        Logout
      </van-button>
    </div>

    <!-- Avatar Action Sheet -->
    <van-action-sheet v-model:show="showAvatarPicker" :actions="avatarActions" @select="onAvatarActionSelect"
      cancel-text="Cancel" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

const logoutLoading = ref(false)

const userInfo = computed(() => userStore.userInfo)

// User stats from API
const userStats = ref({
  level: 1,
  totalPoints: 0,
  streak: 0,
  totalSessions: 0,
  achievements: 0
})

const loading = ref(false)

const sessionProgress = computed(() => {
  return Math.min((userStats.value.totalSessions / 50) * 100, 100)
})

const achievementProgress = computed(() => {
  return Math.min((userStats.value.achievements / 20) * 100, 100)
})

const goToSettings = () => {
  router.push('/profile/settings')
}

const goToTrainingHistory = () => {
  router.push('/profile/training-history')
}

const goToAchievements = () => {
  router.push('/profile/achievements')
}

const goToMyPosts = () => {
  router.push('/profile/posts')
}

const goToFavorites = () => {
  router.push('/profile/favorites')
}

const goToAccountSettings = () => {
  router.push('/profile/settings/account')
}

const goToPrivacySettings = () => {
  router.push('/profile/settings/privacy')
}

const goToHelp = () => {
  router.push('/help')
}

const showAvatarPicker = ref(false)

const avatarActions = [
  { name: 'Take Photo', value: 'camera' },
  { name: 'Choose from Gallery', value: 'gallery' },
  { name: 'Remove Photo', value: 'remove' }
]

const changeAvatar = () => {
  showAvatarPicker.value = true
}

const onAvatarActionSelect = async (action: any) => {
  showAvatarPicker.value = false

  switch (action.value) {
    case 'camera':
      await takePhoto()
      break
    case 'gallery':
      await selectFromGallery()
      break
    case 'remove':
      await removeAvatar()
      break
  }
}

const takePhoto = async () => {
  try {
    // In a real app, this would use camera API
    showToast('Camera feature not available in demo')
    // Simulate photo capture
    // const photo = await navigator.mediaDevices.getUserMedia({ video: true })
    // Process and upload photo
  } catch (error) {
    showToast('Failed to access camera')
  }
}

const selectFromGallery = async () => {
  try {
    // Create file input element
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'

    input.onchange = async (event) => {
      const file = (event.target as HTMLInputElement).files?.[0]
      if (file) {
        await uploadAvatar(file)
      }
    }

    input.click()
  } catch (error) {
    showToast('Failed to select image')
  }
}

const uploadAvatar = async (file: File) => {
  try {
    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      showToast('Image size must be less than 5MB')
      return
    }

    // Validate file type
    if (!file.type.startsWith('image/')) {
      showToast('Please select a valid image file')
      return
    }

    showToast('Uploading avatar...')

    // Upload to server
    const formData = new FormData()
    formData.append('avatar', file)

    console.log('Uploading avatar file:', file.name, file.size, file.type)

    const response = await userApi.uploadAvatar(formData)

    console.log('Avatar upload response:', response)

    if (response.success && response.data) {
      const newAvatarUrl = response.data.avatar_url
      console.log('New avatar URL:', newAvatarUrl)

      // Update user store with new avatar URL
      userStore.updateAvatar(newAvatarUrl)

      console.log('Updated user info:', userStore.userInfo)

      showToast('Avatar updated successfully!')
    } else {
      throw new Error(response.error || 'Upload failed')
    }
  } catch (error) {
    console.error('Avatar upload error:', error)
    showToast('Failed to upload avatar')
  }
}

const removeAvatar = async () => {
  try {
    const result = await showConfirmDialog({
      title: 'Remove Avatar',
      message: 'Are you sure you want to remove your profile picture?'
    })

    if (result === 'confirm') {
      // Update user store
      userStore.updateAvatar('/default-avatar.png')
      showToast('Avatar removed')
    }
  } catch (error) {
    // User cancelled
  }
}

const handleLogout = async () => {
  try {
    const result = await showConfirmDialog({
      title: 'Logout',
      message: 'Are you sure you want to logout?'
    })

    if (result === 'confirm') {
      logoutLoading.value = true
      await userStore.logout()
      showToast('Logged out successfully')
      router.push('/auth/login')
    }
  } catch (error) {
    // User cancelled
  } finally {
    logoutLoading.value = false
  }
}

// Load user data from API
const loadUserData = async () => {
  if (!userInfo.value?.id) return

  try {
    loading.value = true

    // Load user statistics
    const statsResponse = await userApi.getUserStatistics(userInfo.value.id)
    if (statsResponse.success && statsResponse.data) {
      const stats = statsResponse.data
      userStats.value = {
        level: Math.floor(stats.total_sessions / 10) + 1, // Calculate level based on sessions
        totalPoints: Math.round(stats.average_performance * stats.completed_sessions),
        streak: stats.current_streak,
        totalSessions: stats.total_sessions,
        achievements: stats.achievements_count
      }
    }
  } catch (error) {
    console.error('Failed to load user data:', error)
    showToast('Failed to load user data')
  } finally {
    loading.value = false
  }
}

// 刷新用户数据
const refreshUserData = async () => {
  try {
    loading.value = true

    // 从服务器刷新用户信息
    await userStore.refreshUserInfo()

    // 重新加载用户统计数据
    await loadUserData()

    showToast('Profile refreshed successfully')
  } catch (error) {
    console.error('Failed to refresh user data:', error)
    showToast('Failed to refresh profile')
  } finally {
    loading.value = false
  }
}

// Load user data on mount
onMounted(async () => {
  try {
    // Initialize user data from storage if not already loaded
    if (!userInfo.value) {
      userStore.initializeFromStorage()
    }

    // 如果有用户信息，先显示缓存的数据，然后在后台刷新
    if (userInfo.value) {
      // 先加载缓存的统计数据
      await loadUserData()

      // 然后在后台刷新最新数据
      userStore.refreshUserInfo().then(() => {
        // 刷新完用户信息后，重新加载统计数据
        loadUserData()
      }).catch(error => {
        console.error('Background refresh failed:', error)
      })
    } else {
      // 如果没有缓存数据，直接从服务器获取
      await userStore.refreshUserInfo()
      await loadUserData()
    }
  } catch (error) {
    console.error('Failed to load user info:', error)
    showToast('Failed to load profile')
  }
})
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background: $background-color;
}

.user-info-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: $spacing-xl $spacing-md;
  color: $white;
  text-align: center;

  .user-avatar {
    position: relative;
    display: inline-block;
    margin-bottom: $spacing-md;

    .avatar-edit-icon {
      position: absolute;
      bottom: 0;
      right: 0;
      background: $white;
      color: $text-color-3;
      border-radius: 50%;
      padding: 6px;
      box-shadow: $box-shadow-light;
      cursor: pointer;
    }
  }

  .user-details {
    .username {
      font-size: $font-size-xl;
      font-weight: $font-weight-bold;
      margin-bottom: $spacing-xs;
    }

    .user-bio {
      font-size: $font-size-sm;
      opacity: 0.9;
      margin-bottom: $spacing-lg;
    }

    .user-stats {
      display: flex;
      justify-content: center;
      gap: $spacing-xl;

      .stat-item {
        text-align: center;

        .stat-value {
          font-size: $font-size-lg;
          font-weight: $font-weight-bold;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: $font-size-xs;
          opacity: 0.8;
        }
      }
    }
  }
}

.progress-overview {
  padding: $spacing-md;

  .section-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $text-color;
    margin-bottom: $spacing-md;
  }

  .progress-cards {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: $spacing-md;

    .progress-card {
      background: $white;
      border-radius: $border-radius-lg;
      padding: $spacing-md;
      box-shadow: $box-shadow-light;

      .card-header {
        display: flex;
        align-items: center;
        gap: $spacing-xs;
        margin-bottom: $spacing-sm;
        font-size: $font-size-sm;
        color: $text-color-2;
      }

      .card-content {
        .progress-number {
          font-size: $font-size-xl;
          font-weight: $font-weight-bold;
          color: $primary-color;
          margin-bottom: 4px;
        }

        .progress-subtitle {
          font-size: $font-size-xs;
          color: $text-color-3;
          margin-bottom: $spacing-sm;
        }
      }
    }
  }
}

.menu-section,
.settings-section {
  margin: $spacing-md 0;
}

.logout-section {
  padding: $spacing-md;
  margin-top: $spacing-lg;
}

// 刷新按钮动画
.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>